<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/3.3.1/css/bootstrap.css">
    <title>Document</title>
    <style>
     .container{
         margin-top:30px;
     }
     .user{
         color:green;
         cursor: pointer;
     }
    </style>
</head>
<body>
    
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <div class="panel panel-default">
                <div class="panel-heading">
                    <h3 class="text-center">欢迎来到珠峰聊天室</h3>
                    <div class="row">
                        <div class="col-md-6 text-center">
                            <button id="joinred" class="btn btn-danger" onclick="join('red')">进入红房间</button>
                            <button id="leavered" style="display:none" class="btn btn-danger" onclick="leave('red')">退出红房间</button>
                        </div>
                        <div class="col-md-6 text-center">
                            <button  id="joingreen" class="btn btn-success" onclick="join('green')">进入绿房间</button>
                            <button id="leavegreen"  style="display:none" class="btn btn-success" onclick="leave('green')">退出绿房间</button>
                        </div>
                    </div>
                </div>
                <div class="panel-body" id="messagePanel" style="height:500px;overflow-y: auto">
                    <ul class="list-group" id="messageBox" onclick="chooseUser(event)" >

                    </ul>
                </div>
                <div class="panel-footer">
                    <div class="row">
                        <div class="col-md-11">
                            <input type="text" class="form-control" id="textMsg" onkeydown="handleKeyDown(event)">
                        </div>
                        <div class="col-md-1">
                           <button class="btn btn-primary" onclick="send(event)">发言</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


    <script src="/socket.io/socket.io.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/locale/zh-cn.js"></script>
    <script>
       let textMsg = document.getElementById('textMsg');
       let messageBox = document.getElementById('messageBox');
       let messagePanel = document.getElementById('messagePanel');
       let socket = io.connect('/');
       //socket.on('xxx')
       socket.on('connect',function(){
           console.log('连接成功');
           //当连接成功之后客户端可以向服务器发送消息
           //socket.send('hello');
           //socket.emit('message','hello');
           socket.emit('getAllMessages');
       }); 
       function formatMessage(mssageObj){
        return `<span class="user">${mssageObj.username}</span>:${mssageObj.content} <span class="pull-right">${moment(mssageObj.createAt).fromNow()}</span>`;
       }
       window.socket = socket;
       //客户端收到服务器发过来的消息后
       socket.on('message',function(mssageObj){
            let li = document.createElement('li');
            li.innerHTML = formatMessage(mssageObj);
            li.className = 'list-group-item';
            messageBox.appendChild(li);
            messagePanel.scrollTop = messagePanel.offsetHeight;
       });
       socket.on('allMessages',function(messages){
        let html = messages.map(mssageObj=>`<li class="list-group-item">${formatMessage(mssageObj)}</li>`).join('');
        messageBox.innerHTML = html;
        messagePanel.scrollTop = messagePanel.offsetHeight;
       })
       socket.on('disconnect',function(){
           console.log('连接断开');
       });
       socket.on('joined',function(roomName){
        let joinBtn = document.getElementById('join'+roomName);
        let leaveBtn = document.getElementById('leave'+roomName);
        joinBtn.style.display = 'none';
        leaveBtn.style.display = 'inline-block';
       });
       socket.on('leaved',function(roomName){
        let joinBtn = document.getElementById('join'+roomName);
        let leaveBtn = document.getElementById('leave'+roomName);
        joinBtn.style.display = 'inline-block';
        leaveBtn.style.display = 'none';
       });
       function leave(roomName){
         socket.emit('leave',roomName);
       }

       function chooseUser(event){
           if(event.target.className == 'user'){
            let username = event.target.innerText;
              textMsg.value = `@${username} `;
           }
       }
       function handleKeyDown(event){
         if(event.keyCode == 13){//如果说按下的回车键
            send();
         }
       }
       function send(){
        let val = textMsg.value;
        if(val){
            socket.send(val);
            textMsg.value = '';
        }else{
            alert('发言内容不能为空!');
        }
       }
       function join(roomName){
           socket.emit('join',roomName);
       }
    </script>
</body>
</html>